package com.ykt.mall.ctrl;

import java.util.Date;

import org.apache.log4j.Logger;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.ext.route.ControllerBind;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.ykt.mall.content.Content;
import com.ykt.mall.kit.BftPay;
import com.ykt.model.Customer;
import com.ykt.model.Order;
import com.ykt.model.PaymentOrder;

@ControllerBind(controllerKey="/orderPayment")//viewPath="/template"
public class OrderPaymentCtrl extends Controller {
	
	private static Logger logger = Logger.getLogger(ProductCtrl.class);
	
	public void pay(){
		Date date = new Date();
		Integer id = this.getParaToInt("id");
		Order order = Order.dao.findById(id);
		
		Customer cus = getSessionAttr(Content.SESSION_LOGIN_USER);
		int frontSign = cus.getInt("front_sign")==null ? 0 : cus.getInt("front_sign");
		
		Integer payment = order.getInt("payment");//支付方式
		PaymentOrder pay = new PaymentOrder();
		pay.set("order_num", order.get("id"));
		pay.set("amount", order.get("all_money"));
		if(payment ==1 && frontSign==1) pay.set("amount", order.get("front_money"));
		pay.set("version_no", "1");
		pay.set("sign", "0");
		pay.set("create_time", date);
		pay.set("update_time", date);
		pay.set("business_type","1");//业务订单类型(1：商城订单 2：预订订单 3：账号充值)
		pay.save();
		//render("/template/pay_order.html");
		String forward = "/payOrders/result/"+id+"";
		String enShopName = "hyt";
		if(order.getInt("shop_id") == 5){
			enShopName = "yst";
		}
		String toPayUrl = BftPay.payRequest(enShopName, pay, forward, forward);
		redirect(toPayUrl);
	}
	
	/**
	 * 接收支付结果通知
	 */
	@Before(Tx.class)
	public void callback() {
		logger.info("BFT callback start......");
		String returnStr = "T_0000";
		String EncryptMsg=getPara("EncryptMsg");
		/**
		try{
			if (StringKit.notBlank(EncryptMsg)) {
				logger.info("EncryptMsg============>"+EncryptMsg);
				TransData transdata = new TransData();
				PayInforRequest payInforRequest = new PayInforRequest();//声明"支付通知报文"类对象
				transdata=payInforRequest.reveivePayInforRequest(EncryptMsg);//调用"支付通知报文"方法,取各数据元
				if (transdata != null) {
					Date date = new Date();
					logger.info("transdata.getPayID()============>"+transdata.getPayID());
					if(StringKit.notBlank(transdata.getPayID())){
						String payStatusCode = transdata.getSysCode();
						Long paymentId = new Long(transdata.getPayID());
						logger.info("paymentId id:"+paymentId);

						PaymentOrder paymentOrder = PaymentOrder.dao.findById(paymentId);
						String sign = paymentOrder.getStr("sign");
						logger.info("paymentOrder.getSign()====== "+paymentOrder.getStr("sign"));
						
						if(sign==null || "0".equals(sign)){//sign=true已收到支付通知
							
							String bussType = paymentOrder.getStr("business_type");
							int orderId = paymentOrder.getInt("order_num");
							logger.info("payStatusCode========="+payStatusCode+"=======bussType========= "+bussType);
							
							if("1".equals(bussType)){//业务订单类型(1：商城订单 2：预订订单，3：账号充值)
								
								Order order = Order.dao.findById(orderId);
								if ("P_0000".equals(payStatusCode)) {
									//支付成功
									order.set("status", 2);

								}else if("P_00PP".equals(payStatusCode)){
									order.set("status", 1);
								}else {
									order.set("status", 0);//修改订单状态
								}
								order.set("update_time",date);
								order.update();

							}
									
							if ("P_0000".equals(payStatusCode)) {
								paymentOrder.set("status","SUCCESS");
							} else {
								paymentOrder.set("status","FAILED");
							}
							paymentOrder.set("update_time",date);
							paymentOrder.set("sign", "1");
							paymentOrder.update();

							BftNotice bftNotice = new BftNotice();
							try {
								logger.info("Save BftNotice ======");
								bftNotice.set("merid", transdata.getMerID());//取商户平台号
								bftNotice.set("merchantid", transdata.getMerchantID());//商户编号
								bftNotice.set("payid",transdata.getPayID());//取商户订单号
								bftNotice.set("orderamount",transdata.getOrderAmount());//取交易金额
								bftNotice.set("transdate",transdata.getTransDate());//取交易日期
								bftNotice.set("transtime",transdata.getTransTime());//取交易时间
								bftNotice.set("systemssn",transdata.getSystemSSN());//取系统参考号
								bftNotice.set("ylsystemssn",transdata.getYlSystemSSN());//取银联系统参考号
								bftNotice.set("syscode",transdata.getSysCode());//取支付响应码
								bftNotice.set("bankcode",transdata.getBankCode());//取银行代码
								bftNotice.set("bankcard",transdata.getBankCard());//取银行卡号
								bftNotice.set("description",java.net.URLDecoder.decode(transdata.getDescription()));//支付结果描述
								bftNotice.set("transtype",transdata.getTransType());//取交易类型

								bftNotice.save();
								logger.info("Save BftNotice ===OK===");
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					}else{
						returnStr = "T_0014";//报文交互失败,订单号码不存在
					}
				}
			}else{
				returnStr = "T_0095";//报文交互失败,请求格式不正确
			}
			renderText(returnStr);
		}catch(Exception e){
			renderText("T_0096");
			e.printStackTrace();
		}
		**/
		logger.info("BFT callback end......");
	}
	
}
